var Observe = (function () {

    var events = {};//发布列表

    var Observe = {};//先订阅再发布流程

    // 订阅事件
    Observe.subscribe = function (key, callback) {

        // 没有订阅过
        if (!events[key]) {
            events[key] = [];//用于多个订阅者
        }

        // Add the callback to queue
        var index = events[key].push(callback) - 1;//array index

        // 销毁订阅
        return {
            unsubscribe: function () {
                console.log('销毁订阅' + key);
                if(events[key][index]){
                    delete events[key][index];
                    index = null;
                    key = null;
                }else{
                    console.log('已销毁');
                }

                
            }
        };
    };

    // 发布事件
    Observe.emit = function () {//key,data1,data2....
        
        var args = arguments;

        var length = args.length;

        if (length == 0) {
            return;
        }

        var key = args[0];

        // 没有订阅者
        if (!events[key]) {
            return;
        }

        // 订阅callback回调
        events[key].forEach(function (item) {
            if (typeof item != "function") {
                return;
            }
            var fun = "item(";

            for (var i = 1; i < length; i++) {

                try{
                    args[i] = JSON.stringify(args[i]);
                }catch(e){
                    console.log(e);
                }

                if (i == length - 1) {
                    fun += args[i] + ")";
                } else {
                    fun += args[i] + ",";
                }

            }

            eval(fun);

            fun = null,i = null;

        });

        key = null;
        length = null;
        args = null;
    };

    return Observe;

})();